from django import forms
from django.utils import timezone
from datetime import timedelta
from .models import Book, Category

class BookSearchForm(forms.Form):
    """书籍搜索表单"""
    query = forms.CharField(
        max_length=100,
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': '搜索书名、作者、ISBN或出版社...'
        }),
        label='搜索'
    )
    category = forms.ModelChoiceField(
        queryset=Category.objects.all(),
        required=False,
        widget=forms.Select(attrs={'class': 'form-control'}),
        label='分类'
    )
    status = forms.ChoiceField(
        choices=[('', '全部状态')] + Book.STATUS_CHOICES,
        required=False,
        widget=forms.Select(attrs={'class': 'form-control'}),
        label='状态'
    )

class BorrowForm(forms.Form):
    """借阅表单"""
    due_date = forms.DateTimeField(
        widget=forms.DateTimeInput(
            attrs={
                'class': 'form-control',
                'type': 'datetime-local'
            }
        ),
        label='应还日期',
        help_text='请选择预计归还日期'
    )
    notes = forms.CharField(
        max_length=500,
        required=False,
        widget=forms.Textarea(attrs={
            'class': 'form-control',
            'rows': 3,
            'placeholder': '备注信息（可选）'
        }),
        label='备注'
    )
    
    def clean_due_date(self):
        due_date = self.cleaned_data['due_date']
        if due_date <= timezone.now():
            raise forms.ValidationError('应还日期不能早于当前时间')
        if due_date > timezone.now() + timedelta(days=90):
            raise forms.ValidationError('借阅期限不能超过90天')
        return due_date

class BookForm(forms.ModelForm):
    """书籍表单（用于添加/编辑书籍）"""
    class Meta:
        model = Book
        fields = [
            'isbn', 'title', 'author', 'category', 'publisher',
            'publish_date', 'description', 'total_copies', 'location'
        ]
        widgets = {
            'isbn': forms.TextInput(attrs={'class': 'form-control'}),
            'title': forms.TextInput(attrs={'class': 'form-control'}),
            'author': forms.TextInput(attrs={'class': 'form-control'}),
            'category': forms.Select(attrs={'class': 'form-control'}),
            'publisher': forms.TextInput(attrs={'class': 'form-control'}),
            'publish_date': forms.DateInput(attrs={
                'class': 'form-control',
                'type': 'date'
            }),
            'description': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 4
            }),
            'total_copies': forms.NumberInput(attrs={
                'class': 'form-control',
                'min': 1
            }),
            'location': forms.TextInput(attrs={'class': 'form-control'}),
        }
    
    def clean_isbn(self):
        isbn = self.cleaned_data['isbn']
        # 检查ISBN是否已存在（排除当前编辑的书籍）
        if self.instance.pk:
            if Book.objects.filter(isbn=isbn).exclude(pk=self.instance.pk).exists():
                raise forms.ValidationError('该ISBN编号已存在')
        else:
            if Book.objects.filter(isbn=isbn).exists():
                raise forms.ValidationError('该ISBN编号已存在')
        return isbn
    
    def clean_total_copies(self):
        total_copies = self.cleaned_data['total_copies']
        if total_copies < 1:
            raise forms.ValidationError('总数量必须大于0')
        return total_copies

class CategoryForm(forms.ModelForm):
    """分类表单"""
    class Meta:
        model = Category
        fields = ['name', 'description']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'description': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 3
            }),
        } 